<script>
	import {
		baseEnv
	} from '@/utils/config.js';
	import httpInterceptor from '@/common/http.interceptor.js'
	import Downloader from "@/utils/downloader.js";
	import {
		sizeFormate
	} from "@/utils/formate.js";
	import {
		mapState,
		mapMutations
	} from "vuex";


	const globalEvent = uni.requireNativePlugin("globalEvent");
	const {
		platform
	} = uni.getSystemInfoSync();

	const downloadStates = [{
			androidCode: 0,
			iosCode: 0,
			text: "未下载",
		},
		{
			androidCode: 100,
			iosCode: 1,
			text: "等待中",
		},
		{
			androidCode: 200,
			iosCode: 2,
			text: "下载中",
		},
		{
			androidCode: 300,
			iosCode: 3,
			text: "已暂停",
		},
		{
			androidCode: 400,
			iosCode: 4,
			text: "已完成",
		},
		{
			androidCode: 500,
			iosCode: 5,
			text: "下载失败",
		},
	];

	export default {
		globalData: {
			httpRequest: null
		},
		data() {
			return {
				timer: null,
				syncCount: 3, // 同时下载的视频个数
				downloaderInit: false, // 下载器是否已初始化完成
				isConnected: true,
			};
		},
		computed: {
			...mapState({
				downloadList: (state) => state.downloadList,
				finishedDownloadList: (state) => state.finishedDownloadList,
			}),
		},
		onLaunch: function() {
			// #ifdef APP
			// 初始化下载插件
			if (platform === "android") {
				console.log('初始化下载插件', this.downloaderInit)
				uni.$on("getStoragePermission", () => {
					if (!this.downloaderInit) {
						console.log('初始化下载插件')
						Downloader.init({
							userId: '677D7D6D589120DA', // 用户id
							apiKey: 'NrX4nbFDoZkJgOa62lZkf6OhdR0U4MCe', // API KEY
						}, () => {
							this.downloaderInit = true;
						});
					}
				});
			} else {
				Downloader.init({
					userId: '677D7D6D589120DA', // 用户id
					apiKey: 'NrX4nbFDoZkJgOa62lZkf6OhdR0U4MCe', // API KEY
				}, () => {
					this.downloaderInit = true;
				});
			}
			// ios监听下载更新进度
			globalEvent.addEventListener("downloadProgressUpdate", (e) => {
				try {
					if (e) {
						// console.log('downloadProgressUpdate:', JSON.stringify(e));
						let videoItem = this.downloadList.find(
							(item) =>
							item.videoId === e.videoId && item.definition == e.re_quality
						);
						if (videoItem) {
							if (e.subtitle) {
								delete e.subtitle.isDownload;
							}
							Vue.set(videoItem, "cache", e);
							Vue.set(
								videoItem,
								"state",
								downloadStates.find((state) => state.iosCode === e.state).text
							);
							if (e.progress) {
								Vue.set(videoItem, "speed", sizeFormate(e.progress.speed) + "/s");
								Vue.set(
									videoItem,
									"totalSize",
									sizeFormate(e.progress.totalBytesExpectedToWrite)
								);
								Vue.set(
									videoItem,
									"progressPresent",
									e.progress.totalBytesWritten /
									e.progress.totalBytesExpectedToWrite
								);
								Vue.set(
									videoItem,
									"progressText",
									sizeFormate(e.progress.totalBytesWritten) +
									"/" +
									sizeFormate(e.progress.totalBytesExpectedToWrite)
								);
								Vue.set(videoItem, "definitionText", e.definition);
								Vue.set(videoItem, "quality", e.quality);
								Vue.set(videoItem, "re_quality", e.re_quality);
							}
							// 下载完成后，刷新视频队列
							if (e.state === 4) {
								// 从下载列表中移除该项
								if (videoItem.quality == videoItem.re_quality) {
									this.removeDownloadItem(videoItem);
								} else {
									let videoItems = this.downloadList.filter(
										(item) => item.videoId === e.videoId
									);
									videoItems.forEach((item) => {
										this.removeDownloadItem(item);
									});
								}
								// 将该项加入已下载列表
								this.addFinishedDownloadItem(videoItem);
								this.updateScheduler();
							}
						}
					}
				} catch (e) {
					console.log(e);
				}
			});

			// android监听下载更新进度
			globalEvent.addEventListener("onUpdate", (e) => {
				if (e.data) {
					for (let k in e.data) {
						let videoItem = this.downloadList.find(
							(item) =>
							item.videoId === e.data[k].videoId &&
							item.definition == e.data[k].re_quality
						);
						if (videoItem) {
							Vue.set(
								videoItem,
								"state",
								downloadStates.find(
									(state) => state.androidCode === e.data[k].status
								).text
							);
							Vue.set(videoItem, "speed", e.data[k].speed);
							Vue.set(
								videoItem,
								"progressPresent",
								e.data[k].downloadProgressBarValue / 100
							);
							Vue.set(videoItem, "progressText", e.data[k].progressText);
						}
					}
				}
			});
			// android监听下载完成
			globalEvent.addEventListener("onDownloadFinish", (e) => {
				// console.log('onDownloadFinish' + JSON.stringify(e));
				if (e.data) {
					let videoItem = this.downloadList.find(
						(item) =>
						item.videoId === e.data.videoId &&
						item.definition == e.data.re_quality
					);
					if (videoItem) {
						Vue.set(
							videoItem,
							"state",
							downloadStates.find((state) => state.androidCode === e.data.status)
							.text
						);
						Vue.set(videoItem, "speed", "");
						Vue.set(videoItem, "progressText", "");
						Vue.set(videoItem, "totalSize", sizeFormate(e.data.end));
						Vue.set(videoItem, "videoTitle", e.data.fileName);
						Vue.set(videoItem, "format", e.data.format);
						Vue.set(videoItem, "definitionText", e.data.definition);
						Vue.set(videoItem, "quality", e.data.quality);
						Vue.set(videoItem, "re_quality", e.data.re_quality);
						// 下载完成后，刷新视频队列
						// 从下载列表中移除该项
						if (videoItem.quality == videoItem.re_quality) {
							this.removeDownloadItem(videoItem);
						} else {
							let videoItems = this.downloadList.filter(
								(item) => item.videoId === e.data.videoId
							);
							videoItems.forEach((item) => {
								this.removeDownloadItem(item);
							});
						}
						// 将该项加入已下载列表
						this.addFinishedDownloadItem(videoItem);
					}
				}
			});
			// 安卓更新下载进度
			if (platform === "android") {
				this.run();
			}
			uni.$on("startDownload", (data) => {
				console.log('下载视频', this.downloaderInit)
				if (!this.downloaderInit) {
					uni.showToast({
						title: "下载组件初始化失败，请检测网络是否可用",
					});
					return false;
				}
				console.log('下载视频', data)
				if (Array.isArray(data)) {
					data.forEach((item) => {
						let areadyDownloadItem = this.finishedDownloadList.find(
							(finishedItem) =>
							finishedItem.videoId === item.videoId &&
							(finishedItem.definition === item.definition ||
								finishedItem.quality != finishedItem.re_quality)
						);
						if (areadyDownloadItem) {
							this.remove(areadyDownloadItem);
						}
					});
					this.makeDownloadList(data);
				} else {
					let areadyDownloadItem = this.finishedDownloadList.find(
						(finishedItem) =>
						finishedItem.videoId === data.videoId &&
						(finishedItem.definition === data.definition ||
							finishedItem.quality != finishedItem.re_quality)
					);
					console.log('areadyDownloadItem', areadyDownloadItem)
					if (areadyDownloadItem) {
						this.remove(areadyDownloadItem);
					}
					this.addDownloadItem(data);
				}
				setTimeout(() => {
					this.runScheduler();
				}, 1000);
			});
			uni.$on("pauseDownload", (params) => {
				Downloader.pause(params);
			});
			uni.$on("resumeDownload", (params) => {
				Downloader.resume(params);
			});
			uni.$on("deleteDownload", (params) => {
				this.remove(params);
			});
			
			// #endif
		},
		onShow: function() {
			getApp().globalData.httpRequest = this.$u
		},
		onHide: function() {},
		methods: {
			...mapMutations([
				"makeDownloadList",
				"addDownloadItem",
				"addFinishedDownloadItem",
				"removeDownloadItem",
			]),
			start(list) {
				/*
								处理多账号视频下载
								视频按userId分类，然后多次调用start方法
							*/
				let groupList = list.reduce(function(result, item) {
					console.log(result, item);
					if (!result[item.userId]) {
						result[item.userId] = [];
					}
					result[item.userId].push(item);
					return result;
				}, {});
				Object.keys(groupList).forEach((userId) => {
					let apiKey = "",
						verificationCode = "";
					// if (Array.isArray(this.baseInfo)) {
					// 	const item = this.baseInfo.find((i) => i.userId === userId);
					// 	if (item) {
					// 		apiKey = item.apiKey;
					// 		verificationCode = item.verificationCode;
					// 		// this.customId = item.customId
					// 	}
					// } else {
					// 	apiKey = this.baseInfo.apiKey;
					// 	verificationCode = this.baseInfo.verificationCode;
					// 	// this.customId = this.baseInfo.customId
					// }
					apiKey = 'NrX4nbFDoZkJgOa62lZkf6OhdR0U4MCe'
					verificationCode = ''
					let params = {
						userId,
						apiKey,
						verificationCode,
						videoIds: groupList[userId].map((item) => item.videoId),
						definitions: groupList[userId].map((item) => item.definition),
					};
					if (platform === "android") {
						params = groupList[userId].map((item) => {
							return {
								userId,
								apiKey,
								videoId: item.videoId,
								verificationCode,
								downloadTitle: item.videoTitle,
								definition: item.definition,
							};
						});
					}
					// 开始下载
					Downloader.start(params);
				});
			},
			remove(item) {
				console.log("remove action item", item);
				let params;
				try {
					if (platform === "ios") {
						params = item.cache;
						console.log("remove download item params", params);
						if (params) {
							Downloader.delete(params);
						}
					} else {
						if (item.state === "已完成") {
							params = {
								title: item.videoTitle,
								format: item.format,
							};
							console.log("remove download item params", params);
							Downloader.finishedDelete(params);
						} else {
							params = [{
								videoId: item.videoId,
							}];
							console.log("remove download item params", params);
							Downloader.delete(params);
						}
					}
					this.removeDownloadItem(item);
				} catch (e) {
					console.log(e);
				}
			},
			run() {
				this.timer = setInterval(() => {
					this.update();
					if (!this.downloadList.length) {
						clearInterval(this.timer);
						this.timer = null;
					}
				}, 1000);
			},
			update() {
				console.log('下载列表', this.downloadList)
				Downloader.update();
			},
			runScheduler() {
				if (platform === "android") {
					this.start(this.downloadList);
					this.run();
				} else {
					let list = this.downloadList.filter(
						(item) => item.state === "下载中" || item.state === "已暂停"
					); // 正在下载中的视频
					let waitingList = [],
						canDealNum = this.syncCount - list.length;
					// 下载中的视频达到最大，不做处理
					if (canDealNum <= 0) return;
					this.downloadList.forEach((item) => {
						if (canDealNum > 0 && item.state === "等待中") {
							waitingList.push(item);
							canDealNum--;
						}
					});
					// 开始下载
					if (waitingList.length) {
						this.start(waitingList);
					}
				}
			},
			updateScheduler() {
				let list = this.downloadList.filter(
					(item) => item.state === "下载中" || item.state === "已暂停"
				); // 正在下载中的视频
				let next = this.downloadList.find((item) => item.state === "等待中");
				if (next && list.length < this.syncCount) {
					this.start([next]);
				}
			},
		}
	}
</script>

<style lang="scss">
	/* #ifndef APP-NVUE */
	uni-page-body,
	html,
	body {
		height: 100%;
		background: #fff;
	}

	uni-image {
		pointer-events: auto !important;
	}



	// uni-tabbar .uni-tabbar-border {
	//     position: absolute;
	//     left: 0;
	//     top: 0;
	//     width: 100%;
	//     height: 0px;
	//     -webkit-transform: scaleY(.5);
	//     transform: scaleY(.5);
	//     background-color: rgba(0, 0, 0, 0.13) !important;
	// }
	// uni-tabbar.uni-tabbar-bottom .uni-tabbar{
	// 	box-shadow: 0rpx -10rpx 20rpx 0rpx rgba(202,205,217,0.14) !important;
	// }
	.txt {
		overflow: hidden; //超出隐藏
		white-space: nowrap; //不折行
		text-overflow: ellipsis; //溢出显示省略号
	}

	.ml {
		margin-left: auto;
	}

	.txttwo {
		word-break: break-all;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 2;
		/* 超出几行省略 */
		overflow: hidden;
	}

	.ptong {
		padding-left: 20rpx;
		padding-right: 20rpx;
	}

	// .uni-mask {
	// 	background: rgba(0,0,0,1) !important;
	// }
	// /deep/.uni-mask {
	// 	background: transparent;
	// }
	.botview {
		position: fixed;
		width: 100%;
		bottom: 0;
		height: 120rpx;
		background: #FFFFFF;
		box-shadow: 0rpx -10rpx 20rpx 0rpx rgba(202, 205, 217, 0.14);
		display: flex;
		align-items: center;
		padding: 0 30rpx;

		.botbtn {
			height: 80rpx;
			background: linear-gradient(-90deg, #FA4E4E, #FD894F);
			border-radius: 40rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			font-family: PingFangSC;
			font-weight: bold;
			font-size: 28rpx;
			color: #FFFFFF;
			width: 100%;
		}
	}

	.hright {
		position: absolute;
		right: 10px;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;

		.jisuanqi {
			width: 33rpx;
			height: 35rpx;
			position: relative;
			top: 4rpx;
		}

		text {
			font-family: PingFang SC;
			font-weight: 500;
			font-size: 20rpx;
			color: #FD864F;
			display: inline-block;
		}
	}

	/* #endif */
	@import "uview/index.scss";
</style>